//
//  mapView.m
//  Follow Me
//
//  Created by apple on 2017/3/29.
//  Copyright © 2017年 apple. All rights reserved.
//

//#define AppRootViewController  ([[[[UIApplication sharedApplication] delegate] window] rootViewController])

#import "mapView.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "takePhoto.h"
#import "MainModel.h"
#import "Routes+CoreDataClass.h"
#import "Photos+CoreDataClass.h"
#import "Users+CoreDataClass.h"

@interface mapView ()<MKMapViewDelegate,CLLocationManagerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, assign)CGRect leftRect;
@property (nonatomic, assign)CGRect middleRect;
@property (nonatomic, assign)CGRect rightRect;
@property (nonatomic, assign)CGRect leftMiddleRect;
@property (nonatomic, assign)CGRect RightMiddleRect;

@property(nonatomic,strong)NSTimer *timer;


@property (strong, nonatomic) IBOutlet UIButton *startRecord;
@property (strong, nonatomic) IBOutlet UIButton *cameraButton;
@property (strong, nonatomic) IBOutlet UIButton *stopRecord;
@property (strong, nonatomic) IBOutlet UIButton *pauseRecord;
@property (strong, nonatomic) IBOutlet UIButton *continueRecord;
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (nonatomic,strong) CLLocationManager *locationManager;
@property (nonatomic,strong) NSMutableArray *locationMutableArray;
@property (strong, nonatomic) IBOutlet UIButton *followButton;
@property (nonatomic,strong) NSData *tempImageData;
@property (nonatomic) NSInteger countID;
@end

@implementation mapView


-(void) awakeFromNib{
    [super awakeFromNib];
    
    self.middleRect = self.startRecord.frame;
    self.leftRect = CGRectMake(89, 538, 60, 60);
    self.rightRect = CGRectMake(225, 538, 60, 60);
    self.leftMiddleRect = CGRectMake(123.5, 538, 60, 60);
    self.RightMiddleRect = CGRectMake(191.5, 538, 60, 60);
    self.cameraButton.hidden = YES;
    self.stopRecord.hidden = YES;
    self.pauseRecord.hidden = YES;
    self.continueRecord.hidden = YES;
    
    self.mapView.delegate = self;
   
    
    
    self.locationManager = [[CLLocationManager alloc]init];
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager requestAlwaysAuthorization];
    self.mapView.showsUserLocation = true;
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [self.mapView setMapType:MKMapTypeHybridFlyover];
    self.mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
    
//    //存放位置的数组
//    self.locationMutableArray = [[NSMutableArray alloc]init];
    
    
//    NSLog(@"开始定位");
//    //调用 startUpdatingLocation 方法后,会对应进入 didUpdateLocations 方法
//    [self.locationManager startUpdatingLocation];

    
    isStop = YES;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self  selector:@selector(startTimer) userInfo:nil repeats:YES ];
    [self.timer setFireDate:[NSDate distantFuture]];
    
    
    
    
}




-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    
//    NSString *latitude = [NSString stringWithFormat:@"%3.5f",userLocation.coordinate.latitude];
//    NSString *longitude = [NSString stringWithFormat:@"%3.5f",userLocation.coordinate.longitude];
//    NSLog(@"更新的用户位置:纬度:%@, 经度:%@",latitude,longitude);
    
//    //设置地图显示范围(如果不进行区域设置会自动显示区域范围并指定当前用户位置为地图中心点)
//    MKCoordinateSpan span = MKCoordinateSpanMake(0.05, 0.05);
//    MKCoordinateRegion region=MKCoordinateRegionMake(userLocation.location.coordinate, span);
//    [_mapView setRegion:region animated:true];
    
    if (self.locationMutableArray.count > 1&&isStop == NO) {
        
        //从位置数组中取出最新的位置数据
        NSString *locationStr = _locationMutableArray.lastObject;
        NSArray *temp = [locationStr componentsSeparatedByString:@","];
        NSString *latitudeStr = temp[0];
        NSString *longitudeStr = temp[1];
        CLLocationCoordinate2D startCoordinate = CLLocationCoordinate2DMake([latitudeStr doubleValue], [longitudeStr doubleValue]);
        
        //当前确定到的位置数据
        CLLocationCoordinate2D endCoordinate;
        endCoordinate.latitude = userLocation.coordinate.latitude;
        endCoordinate.longitude = userLocation.coordinate.longitude;
        
        //移动距离的计算
        double meters = [self calculateDistanceWithStart:startCoordinate end:endCoordinate];
        tempDistance = meters;
//        kiloMeter = meters/1000;
        NSLog(@"移动的距离为%f米",meters);
        
        
        //为了美化移动的轨迹,移动的位置超过10米,方可添加进位置的数组
        if (meters >= 15){
            
            NSLog(@"添加进位置数组");
            NSString *locationString = [NSString stringWithFormat:@"%f,%f",userLocation.coordinate.latitude, userLocation.coordinate.longitude];
            [self.locationMutableArray addObject:locationString];
            self.locationArray = self.locationMutableArray;
                    //开始绘制轨迹
            CLLocationCoordinate2D pointsToUse[2];
            pointsToUse[0] = startCoordinate;
            pointsToUse[1] = endCoordinate;
            //调用 addOverlay 方法后,会进入 rendererForOverlay 方法,完成轨迹的绘制
            MKPolyline *lineOne = [MKPolyline polylineWithCoordinates:pointsToUse count:2];
            [_mapView addOverlay:lineOne];
            NSLog(@"啊啊啊啊啊，我要开始画线了！！！！！");
            
        }else{
            
            NSLog(@"不添加进位置数组");
        }
    }else {
        
        //存放位置的数组,如果数组包含的对象个数为0,那么说明是第1次进入,将当前的位置添加到位置数组
        if(userLocation.coordinate.latitude!=0.00000&&userLocation.coordinate.longitude!=0.00000){
        NSString *locationString = [NSString stringWithFormat:@"%f,%f",userLocation.coordinate.latitude, userLocation.coordinate.longitude];
        [_locationMutableArray addObject:locationString];
        }
    }
}


//画线
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay{
    
    if ([overlay isKindOfClass:[MKPolyline class]]){
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
        MKPolylineView *polyLineView = [[MKPolylineView alloc] initWithPolyline:overlay];
        polyLineView.lineWidth = 10; //折线宽度
        polyLineView.strokeColor = [UIColor yellowColor]; //折线颜色
        return (MKOverlayRenderer *)polyLineView;
#pragma clang diagnostic pop
    }
    
    return nil;
}


- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    // 设备的当前位置
    CLLocation *currLocation = [locations lastObject];
    
    NSString *latitude = [NSString stringWithFormat:@"纬度:%3.5f",currLocation.coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"经度:%3.5f",currLocation.coordinate.longitude];
    NSString *altitude = [NSString stringWithFormat:@"高度值:%3.5f",currLocation.altitude];
    
    NSLog(@"位置发生改变:纬度:%@,经度:%@,高度:%@",latitude,longitude,altitude);
    
    [manager stopUpdatingLocation];
}

#pragma mark - 距离测算
- (double)calculateDistanceWithStart:(CLLocationCoordinate2D)start end:(CLLocationCoordinate2D)end {
    
    double meter = 0;
    
    double startLongitude = start.longitude;
    double startLatitude = start.latitude;
    double endLongitude = end.longitude;
    double endLatitude = end.latitude;
    
    double radLatitude1 = startLatitude * M_PI / 180.0;
    double radLatitude2 = endLatitude * M_PI / 180.0;
    double a = fabs(radLatitude1 - radLatitude2);
    double b = fabs(startLongitude * M_PI / 180.0 - endLongitude * M_PI / 180.0);
    
    double s = 22 * asin(sqrt(pow(sin(a/2),2) + cos(radLatitude1) * cos(radLatitude2) * pow(sin(b/2),2)));
    s = s * 6378137;
    
    meter = round(s * 10000) / 10000;
     //kiloMeter =meter/1000;
    return meter;
}

//开始计时
-(void)startTimer{
    persent++;
    if(persent == 100){
        seconds++;
        persent = 0;
        
    }
    if(seconds == 60){
        minutes++;
        seconds = 0;
        
    }
    if(minutes ==60 ){
        hours++;
        minutes = 0;
        
    }
    
    self.timeCount.text = [NSString stringWithFormat:@"%02d:%02d:%02d",hours,minutes,seconds];
}

//位置更新时改变距离
- (void)setLocationArray:(NSArray *)locationArray
{
    _locationArray = locationArray;
    kiloMeter = kiloMeter+(tempDistance/1000);
   self.lengthOfRoute.text = [NSString stringWithFormat:@"%.3f Km",kiloMeter];
    
}

- (IBAction)followStart:(id)sender {
    self.mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
}

//开始记录
- (IBAction)startRecording:(id)sender {
    
    //创建Routes
    Routes *route = [Routes createEntity];
    [MainModel model].routeMsg = route;
    NSArray *numRou = [Routes findAll];
    self.countID = numRou.count+1;
    route.keyID = self.countID;
    
    self.startRecord.hidden = YES;
    self.pauseRecord.hidden = NO;
    self.cameraButton.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        self.pauseRecord.frame = self.leftMiddleRect;
        self.cameraButton.frame = self.RightMiddleRect;
        self.startRecord.frame = self.leftRect;
    }completion:^(BOOL finished)
     {
         
     }];
    
    if(isStop){
        [self.timer setFireDate:[NSDate date]];
        isStop = NO;
    }else{
        [self.timer setFireDate:[NSDate distantFuture]];
        isStop = YES;
    }
    
   
    
    NSLog(@"开始定位");
    //调用 startUpdatingLocation 方法后,会对应进入 didUpdateLocations 方法
    [self.locationManager startUpdatingLocation];
    //存放位置的数组
    self.locationMutableArray = [[NSMutableArray alloc]init];
    
    
    
    
}

//拍照
- (IBAction)takePhotos:(id)sender {

    
    [takePhoto sharePicture:^(UIImage *HeadImage){
        
        self.tempImageData = UIImageJPEGRepresentation(HeadImage,0.1);
        Photos *photos = [Photos createEntity];
        photos.photoData = _tempImageData;
        photos.route = [MainModel model].routeMsg;
        photos.rouID = self.countID;
        [[NSManagedObjectContext defaultContext] saveOnlySelfWithCompletion:^(BOOL success, NSError *error) {
            NSLog(@"%@",photos);
            
        }];

//        [self.cameraButton setBackgroundImage:HeadImage forState:UIControlStateNormal];
        
    }];
   

    
}



//暂停
- (IBAction)pauseRecording:(id)sender {
    
    self.pauseRecord.hidden = YES;
    self.stopRecord.hidden = NO;
    self.continueRecord.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        
        self.stopRecord.frame = self.leftRect;
        self.continueRecord.frame = self.middleRect;
        self.cameraButton.frame = self.rightRect;
        self.pauseRecord.frame = self.leftRect;
    }completion:^(BOOL finished)
     {
         
     }];
    [self.timer setFireDate:[NSDate distantFuture]];
    
    
    //暂停位置更新
    isStop = YES;
    //[self.locationManager stopUpdatingLocation];
}


//继续
- (IBAction)continueRecording:(id)sender {
    self.pauseRecord.hidden = NO;
    self.stopRecord.hidden = YES;
    self.continueRecord.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        
        self.stopRecord.frame = self.leftMiddleRect;
        self.continueRecord.frame = self.leftMiddleRect;
        self.cameraButton.frame = self.RightMiddleRect;
        self.pauseRecord.frame = self.leftMiddleRect;
    }completion:^(BOOL finished)
     {
         
     }];
    
    [self.timer setFireDate:[NSDate date]];
    //继续位置更新
    isStop = NO;
//    [self.locationManager startUpdatingLocation];
}


//结束
- (IBAction)stopRecording:(UIButton *)sender {

    NSString *tt =@"helloworld";
    if ([self.delegate respondsToSelector:@selector(actionOut:)]) {
        [self.delegate actionOut:tt];}

    
    isStop = YES;
}


//保存或不保存都恢复button的位置
-(void)saveOrNot
{
    self.stopRecord.hidden = YES;
    self.continueRecord.hidden = YES;
    self.cameraButton.hidden = YES;
    self.startRecord.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        
        self.startRecord.frame = self.middleRect;
        self.continueRecord.frame = self.leftMiddleRect;
        self.cameraButton.frame = self.middleRect;
        self.pauseRecord.frame = self.middleRect;
        self.stopRecord.frame = self.leftMiddleRect;
    }completion:^(BOOL finished)
     {
         
     }];
    
    kiloMeter = 0;
    persent = 0;
    seconds = 0;
    minutes = 0;
    hours = 0;
    self.timeCount.text = [NSString stringWithFormat:@"%02d:%02d:%02d",seconds,minutes,hours];
    self.lengthOfRoute.text = [NSString stringWithFormat:@"%.3f Km",kiloMeter];
}




//
//#pragma mark -- MenuView
//- (IBAction)onMenu:(id)sender {
//    if (!self.menu) {
//        self.menu = [[NSBundle mainBundle] loadNibNamed:@"MenuView" owner:self options:nil].firstObject;
//        self.menu.delegate = self;
//    }
//    //[self.view addSubview:self.menu];
//}
//
- (void)selectedMenuItem:(NSInteger)index
{
    NSLog(@"you selected ::: %ld item",index);
    self.startRecord.hidden = YES;
}










@end
